<?php

namespace App\Http\Middleware;

use App\Exceptions\InvalidRequestException;
use App\Http\Admin\Services\AuthService;
use Closure;
use Illuminate\Support\Facades\Auth;


class AdminAuth
{

    public function handle($request, Closure $next)
    {
        $uri = $request->getRequestUri();
        $flag = strpos($uri,'?');
        if($flag ){
            $uri = explode('?',$uri)[0];
        }
        $token = $request->input('token', null);
        if (!$token) {
            throw new InvalidRequestException('无token信息');
        }
        $user = $this->hasNext($token,$uri);

        if($user){
            $_SERVER['current_user'] = $user;
            return $next($request);
        }

        return err('您没有权限',[],403);
    }

    public function hasNext($token,$uri){
        $user = false;
        //获取当前用户所有的权限
        $authService = new AuthService();
        $user = $authService->initUser($token);
        if(!empty($user->permission_paths)){
            //如果是超级管理员就直接走下去
            if(in_array('超级管理员',$user->roles_names)){
                return $user;
            }
            //权限校验
            $permissions = $user->permission_paths;
            if(in_array($uri,$permissions)){
                return $user;
            }
        }
        return [];
    }


}
